<?php

namespace backend\controllers;

use backend\models\Patch;
use backend\models\SvnFile;
use Yii;
use backend\models\Svn;
use backend\models\SvnSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * SvnController implements the CRUD actions for Svn model.
 */
class SvnController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Svn models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SvnSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel'  => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Svn model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
    {
        $model = new Svn();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->renderAjax('create', [
            'model' => $model,
        ]);
    }

    // /**
    //  * Creates a new Svn model.
    //  * If creation is successful, the browser will be redirected to the 'view' page.
    //  * @return mixed
    //  * @throws \yii\db\Exception
    //  */
    // public function actionCreate()
    // {
    //     $model = new Svn();
    //
    //     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    //         $transaction = Yii::$app->db->beginTransaction();
    //         try {
    //             $model->save(false);
    //             $svnId = $model->id;
    //
    //             $data = [];
    //             foreach ($model->file as $file_id) {
    //                 $data[] = [$svnId, $file_id];
    //             }
    //             Yii::$app->db
    //                 ->createCommand()
    //                 ->batchInsert(SvnFile::tableName(), ['svn_id', 'file_id'], $data)
    //                 ->execute();
    //
    //             $transaction->commit();
    //         } catch (\Exception $e) {
    //             $transaction->rollBack();
    //             throw $e;
    //         }
    //         return $this->redirect(['view', 'id' => $model->id]);
    //     }
    //
    //     return $this->render('create', [
    //         'model'      => $model,
    //         'patchModel' => new Patch(),
    //     ]);
    // }

    /**
     * Updates an existing Svn model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Svn model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Svn model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Svn the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Svn::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }

    public function actionSearchSvn(?string $q = null)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = [
            'results' => ['id' => '', 'text' => ''],
        ];

        $data = Svn::find()
            ->select('id, comment as text')
            ->andFilterWhere(['like', 'comment', $q])
            ->limit(10)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }
}
